<template>
  <div class="app-container">
    <!-- 基本信息 -->
    <div class="block-container">
      <div class="block-title">基本信息</div>
      <div class="basic-info-container">
        <!-- 左侧表单 -->
        <div class="form-section">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <!-- 基本信息表单内容 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="房屋名称" prop="houseName">
                  <el-input v-model="form.houseName" placeholder="请输入房屋名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="房屋编号" prop="houseCode">
                  <el-input v-model="form.houseCode" placeholder="请输入房屋编号" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="项目名称" prop="projectId">
                  <el-select 
                    v-model="form.projectId" 
                    placeholder="请选择项目" 
                    clearable 
                    filterable 
                    :filter-method="filterProjects"
                    @clear="handleProjectClear"
                  >
                    <el-option
                      v-for="item in projectOptions"
                      :key="item.projectId"
                      :label="item.projectName"
                      :value="item.projectId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="省份" prop="province">
                  <el-select v-model="form.province" placeholder="请选择省份" @change="handleProvinceChange">
                    <el-option
                      v-for="item in provinceOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="城市" prop="city">
                  <el-select v-model="form.city" placeholder="请选择城市" @change="handleCityChange">
                    <el-option
                      v-for="item in cityOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="区域" prop="district">
                  <el-select v-model="form.district" placeholder="请选择区域" @change="handleDistrictChange">
                    <el-option
                      v-for="item in districtOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="街道" prop="street">
                  <el-select v-model="form.street" placeholder="请选择街道" @change="handleStreetChange">
                    <el-option
                      v-for="item in streetOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="居委" prop="community">
                  <el-select 
                    v-model="form.community" 
                    placeholder="请选择居委" 
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in committeeOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="详细地址" prop="address" style="width: 100%;">
                  <el-input 
                    v-model="form.address" 
                    placeholder="请输入详细地址" 
                    @blur="handleAddressChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input-number
                    v-model="form.longitude"
                    :precision="6"
                    :step="0.000001"
                    :controls="false"
                    placeholder="请输入经度"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input-number
                    v-model="form.latitude"
                    :precision="6"
                    :step="0.000001"
                    :controls="false"
                    placeholder="请输入纬度"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="负责人" prop="manager" style="width: 100%;">
                  <el-select
                    v-model="form.manager"
                    multiple
                    filterable
                    placeholder="请输入关键词搜索"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in userOptions"
                      :key="item.userId"
                      :label="item.nickName"
                      :value="item.userName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <!-- 右侧地图区域 -->
        <div class="map-section">
          <!-- <baidu-map
            ref="baiduMap"
            :longitude="form.longitude"
            :latitude="form.latitude"
            :editable="true"
            @marker-move="handleMarkerMove" 
          /> -->
          <a-map
            ref="aMap"
            :longitude="form.longitude"
            :latitude="form.latitude"
            :zoom="15"
            :editable="true"
            @marker-move="handleMarkerMove"
          ></a-map>

        </div>
      </div>
    </div>

    <!-- 房屋信息 -->
    <div class="block-container">
      <div class="block-title">房屋信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 房屋信息表单内容 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="土地证号" prop="landCertificate">
              <el-input v-model="form.landCertificate" placeholder="请输入土地证号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="占地面积(m²)" prop="landArea">
              <el-input-number
                v-model="form.landArea"
                :precision="2"
                :step="0.01"
                :controls="false"
                placeholder="请输入占地面积"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="土地性质" prop="landNature">
              <el-select v-model="form.landNature" placeholder="请选择土地性质">
                <el-option
                  v-for="dict in dict.type.house_land_nature"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="产权性质" prop="propertyNature">
              <el-select v-model="form.propertyNature" placeholder="请选择产权性质">
                <el-option
                  v-for="dict in dict.type.house_property_nature"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产权单位" prop="propertyOwner">
              <el-input v-model="form.propertyOwner" placeholder="请输入产权单位（人）" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产权证号" prop="propertyCertificate">
              <el-input v-model="form.propertyCertificate" placeholder="请输入产权证号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="公房面积(m²)" prop="publicArea">
              <el-input-number
                v-model="form.publicArea"
                :precision="2"
                :step="0.01"
                :controls="false"
                placeholder="请输入公房面积"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="售后面积(m²)" prop="afterSaleArea">
              <el-input-number
                v-model="form.afterSaleArea"
                :precision="2"
                :step="0.01"
                :controls="false"
                placeholder="请输入售后房面积"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="公房户数" prop="publicHouseCount">
              <el-input-number
                v-model="form.publicHouseCount"
                :min="0"
                :controls="false"
                placeholder="请输入直管公房数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="售后户数" prop="afterSaleCount">
              <el-input-number
                v-model="form.afterSaleCount"
                :min="0"
                :controls="false"
                placeholder="请输入售后房户数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他户数" prop="otherTypeCount">
              <el-input-number
                v-model="form.otherTypeCount"
                :min="0"
                :controls="false"
                placeholder="请输入其他类型户数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="主用人数" prop="mainUserCount">
              <el-input-number
                v-model="form.mainUserCount"
                :min="0"
                :controls="false"
                placeholder="请输入主用人数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="建筑面积(m²)" prop="buildingArea">
              <el-input-number
                v-model="form.buildingArea"
                :precision="2"
                :step="0.01"
                :controls="false"
                placeholder="请输入建筑面积"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="建造日期" prop="buildDate">
              <el-date-picker
                v-model="form.buildDate"
                type="date"
                placeholder="选择建造日期"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设计年限" prop="designLife">
              <el-input-number
                v-model="form.designLife"
                :min="0"
                :controls="false"
                placeholder="请输入设计年限"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="建筑高度" prop="buildingHeight">
              <el-input-number
                v-model="form.buildingHeight"
                :precision="2"
                :step="0.01"
                :controls="false"
                placeholder="请输入建筑高度"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总层数" prop="totalFloors">
              <el-input-number
                v-model="form.totalFloors"
                :min="0"
                :controls="false"
                placeholder="请输入总层数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地上层数" prop="aboveFloors">
              <el-input-number
                v-model="form.aboveFloors"
                :min="0"
                :controls="false"
                placeholder="请输入地上层数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="地下层数" prop="underFloors">
              <el-input-number
                v-model="form.underFloors"
                :min="0"
                :controls="false"
                placeholder="请输入地下层数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单元总数" prop="unitCount">
              <el-input-number
                v-model="form.unitCount"
                :min="0"
                :controls="false"
                placeholder="请输入单元总数"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结构类型" prop="structureType">
              <el-select v-model="form.structureType" placeholder="请选择结构类型">
                <el-option
                  v-for="dict in dict.type.house_structure_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="地基类型" prop="foundationType">
              <el-select v-model="form.foundationType" placeholder="请选择地基类型">
                <el-option
                  v-for="dict in dict.type.house_foundation_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房屋用途" prop="houseUsage">
              <el-select v-model="form.houseUsage" placeholder="请选择房屋用途">
                <el-option
                  v-for="dict in dict.type.house_usage_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="房屋类型" prop="houseType">
              <el-select v-model="form.houseType" placeholder="请选择房屋类型">
                <el-option
                  v-for="dict in dict.type.house_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="电梯设施" prop="hasElevator">
              <el-select v-model="form.hasElevator" placeholder="请选择是否有电梯设施">
                <el-option label="无" value="0" />
                <el-option label="有" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="消防设施" prop="hasFireProtection">
              <el-select v-model="form.hasFireProtection" placeholder="请选择是否有消防设施">
                <el-option label="无" value="0" />
                <el-option label="有" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设计单位" prop="designUnit">
              <el-input v-model="form.designUnit" placeholder="请输入设计单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="总户数" prop="totalHouseholds">
              <el-input-number
                v-model="form.totalHouseholds"
                :min="0"
                :controls="false"
                placeholder="请输入总户数"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 房屋照片 -->
    <div class="block-container">
      <div class="block-title">房屋照片</div>
      <el-form :model="form" label-width="100px">
        <el-form-item>
          <el-upload
            action="#"
            :auto-upload="false"
            :file-list="photoList"
            :before-upload="handleBeforeUpload"
            :on-change="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :on-exceed="handleUploadExceed"
            :limit="10"
            multiple
            list-type="picture-card"
            accept=".jpg,.jpeg,.png"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>

    <!-- 评估信息 -->
    <div class="block-container">
      <div class="block-title">评估信息</div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- 评估信息表单内容 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="鉴定等级" prop="appraisalLevel">
              <el-select v-model="form.appraisalLevel" placeholder="请选择鉴定等级">
                <el-option
                  v-for="dict in dict.type.house_appraisal_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排查等级" prop="inspectionLevel">
              <el-select v-model="form.inspectionLevel" placeholder="请选择排查等级">
                <el-option
                  v-for="dict in dict.type.house_inspection_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="抗震等级" prop="seismicLevel">
              <el-select v-model="form.seismicLevel" placeholder="请选择抗震等级">
                <el-option
                  v-for="dict in dict.type.house_seismic_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="风险等级" prop="riskLevel">
              <el-select v-model="form.riskLevel" placeholder="请选择风险等级">
                <el-option
                  v-for="dict in dict.type.house_risk_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="减隔震" prop="shockAbsorption">
              <el-select v-model="form.shockAbsorption" placeholder="请选择是否采用减隔震">
                <el-option
                  v-for="dict in dict.type.house_shock_absorption"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保护建筑" prop="isProtected">
              <el-select v-model="form.isProtected" placeholder="请选择是否保护性建筑">
                <el-option
                  v-for="dict in dict.type.house_protected_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="改造方式" prop="isReformed">
              <el-select v-model="form.isReformed" placeholder="请选择改造方式">
                <el-option label="未改造" value="0" />
                <el-option label="已改造" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物业管理" prop="hasProperty">
              <el-select v-model="form.hasProperty" placeholder="请选择是否有物业管理">
                <el-option label="无" value="0" />
                <el-option label="有" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-if="form.isReformed === '1'">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="改造单位" prop="reformDesignUnit">
                <el-input v-model="form.reformDesignUnit" placeholder="请输入改造设计单位" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="改造时间" prop="reformTime">
                <el-date-picker
                  v-model="form.reformTime"
                  type="date"
                  placeholder="选择改造时间"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="改造内容" prop="reformContent">
                <el-input
                  type="textarea"
                  v-model="form.reformContent"
                  placeholder="请输入改造内容"
                  :rows="3"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remark">
              <el-input
                type="textarea"
                v-model="form.remark"
                placeholder="请输入备注说明"
                :rows="3"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="bottom-control">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { getHouse, addHouse, updateHouse } from "@/api/house/house";
import { listHousePhoto, uploadHousePhoto, delHousePhoto, getPhotoUrl } from "@/api/house/housePhoto";
import { getToken } from '@/utils/auth'
import { listProvinceOptions } from "@/api/house/province";
import { listCityOptions } from "@/api/house/city";
import { listDistrictOptions } from "@/api/house/district";
import { listStreetOptions } from "@/api/house/street";
import { listCommitteeOptions } from "@/api/house/committee";
import { listProjects } from "@/api/house/project";
import BaiduMap from '@/components/BaiduMap'
import AMap from '@/components/AMap'
import { listUser } from "@/api/system/user";

export default {
  name: "HouseForm",
  components: {
    BaiduMap,
    AMap
  },
  dicts: [
    'house_risk_level',
    'house_structure_type',
    'house_usage_type',
    'house_land_nature',
    'house_property_nature',
    'house_foundation_type',
    'house_type',
    'house_inspection_level',
    'house_appraisal_level',
    'house_seismic_level',
    'house_shock_absorption',
    'house_protected_type'
  ],
  data() {
    return {
      // 标题
      title: "",
      // 表单参数
      form: {
        houseName: '',
        houseCode: '',
        projectId: null,
        province: null,
        city: null,
        district: null,
        street: null,
        community: '',
        address: '',
        manager: [],
        // ... 其他字段的初始值
      },
      // 表单校验
      rules: {
        houseName: [
          { required: true, message: "房屋名称不能为空", trigger: "blur" }
        ],
        houseCode: [
          { required: true, message: "房屋编号不能为空", trigger: "blur" }
        ],
        projectId: [
          { required: true, message: "项目名称不能为空", trigger: "change" }
        ],
        address: [
          { required: true, message: "地址不能为空", trigger: "blur" }
        ]
      },
      // 激活的标签页
      activeTab: 'basic',
      // 照片列表
      photoList: [],
      // 上传参数
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/house/photo/upload"
      },
      // 省市区数据
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      streetOptions: [],
      committeeOptions: [],
      deletedPhotoIds: [],
      // 项目选项
      projectOptions: [],
      projectOptionsBackup: [], // 用于筛选功能
      userOptions: [], // 用户选项
    };
  },
  created() {
    const houseId = this.$route.params.houseId;
    this.title = houseId ? "修改房屋" : "新增房屋";
    if (houseId) {
      this.getHouseData(houseId);
    }
    this.loadProvinceOptions();
    this.loadProjectOptions();

    // 处理路由参数中的项目ID
    const { projectId, projectName } = this.$route.query;
    if (projectId && !houseId) { // 只在新增时处理路由参数
      this.form.projectId = projectId;
      if (projectName) {
        const projectOption = {
          projectId: projectId,
          projectName: projectName
        };
        this.projectOptions = [projectOption];
        this.projectOptionsBackup = [projectOption];
      }
    }
    this.loadAllUsers(); // 加载所有用户
  },
  methods: {
    /** 获取房屋数据 */
    getHouseData(houseId) {
      // 先加载项目选项
      return listProjects({ pageSize: 1000 }).then(projectResponse => {
        this.projectOptions = projectResponse.rows;
        this.projectOptionsBackup = [...this.projectOptions];
        
        // 再获取房屋数据
        return getHouse(houseId).then(async response => {
          this.form = response.data;
          // 按顺序加载省市区街道数据
          if (this.form.province) {
            await this.loadCityOptions(this.form.province);
          }
          if (this.form.city) {
            await this.loadDistrictOptions(this.form.city);
          }
          if (this.form.district) {
            await this.loadStreetOptions(this.form.district);
          }
          if (this.form.street) {
            await this.loadCommitteeOptions(this.form.street);
          }
          // 获取照片列表
          this.getPhotoList(houseId);
        });
      });
    },
    /** 加载省份数据 */
    loadProvinceOptions() {
      listProvinceOptions().then(response => {
        this.provinceOptions = response.rows.map(item => ({
          value: item.provinceCode,
          label: item.provinceName
        }));
      });
    },
    /** 加载城市数据 */
    loadCityOptions(provinceCode) {
      return listCityOptions({ provinceCode: provinceCode }).then(response => {
        this.cityOptions = response.rows.map(item => ({
          value: item.cityCode,
          label: item.cityName
        }));
      });
    },
    /** 加载区域数据 */
    loadDistrictOptions(cityCode) {
      return listDistrictOptions({ cityCode: cityCode }).then(response => {
        this.districtOptions = response.rows.map(item => ({
          value: item.districtCode,
          label: item.districtName
        }));
      });
    },
    /** 加载街道数据 */
    loadStreetOptions(districtCode) {
      return listStreetOptions({ districtCode: districtCode }).then(response => {
        this.streetOptions = response.rows.map(item => ({
          value: item.streetCode,
          label: item.streetName
        }));
      });
    },
    /** 加载居委数据 */
    loadCommitteeOptions(streetCode) {
      if (!streetCode) {
        this.committeeOptions = [];
        this.form.community = '';
        return Promise.resolve();
      }
      return listCommitteeOptions({ streetCode: streetCode, pageSize: 100 }).then(response => {
        this.committeeOptions = response.rows.map(item => ({
          value: String(item.committeeCode),
          label: item.committeeName
        }));
      });
    },
    /** 省份选择改变事件 */
    handleProvinceChange(value) {
      if (value) {
        this.loadCityOptions(value);
        this.form.city = null;
        this.form.district = null;
        this.form.street = null;
        this.form.community = '';
        this.cityOptions = [];
        this.districtOptions = [];
        this.streetOptions = [];
        this.committeeOptions = [];
        this.updateMapLocation();
      }
    },
    /** 城市选择改变事件 */
    handleCityChange(value) {
      if (value) {
        this.loadDistrictOptions(value);
        this.form.district = null;
        this.form.street = null;
        this.form.community = '';
        this.districtOptions = [];
        this.streetOptions = [];
        this.committeeOptions = [];
        this.updateMapLocation();
      }
    },
    /** 区域选择改变事件 */
    handleDistrictChange(value) {
      if (value) {
        this.loadStreetOptions(value);
        this.form.street = null;
        this.form.community = '';
        this.streetOptions = [];
        this.committeeOptions = [];
        this.updateMapLocation();
      }
    },
    /** 街道选择改变事件 */
    handleStreetChange(value) {
      console.log('街道改变:', value);
      this.committeeOptions = [];
      this.form.community = '';
      
      if (value) {
        this.loadCommitteeOptions(value).then(() => {
          console.log('当前社区值:', this.form.community);
          console.log('可选项:', this.committeeOptions);
          this.updateMapLocation();
        });
      }
    },
    /** 重置地址选项 */
    resetAddressOptions() {
      this.cityOptions = [];
      this.districtOptions = [];
      this.streetOptions = [];
      this.committeeOptions = [];
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 创建提交数据对象，包含所有表单数据
          const submitData = { ...this.form };
          
          // 处理布尔值转换
          if (submitData.hasElevator !== undefined) {
            submitData.hasElevator = submitData.hasElevator === '1' ? '1' : '0';
          }
          if (submitData.hasFireProtection !== undefined) {
            submitData.hasFireProtection = submitData.hasFireProtection === '1' ? '1' : '0';
          }
          if (submitData.hasProperty !== undefined) {
            submitData.hasProperty = submitData.hasProperty === '1' ? '1' : '0';
          }
          if (submitData.isReformed !== undefined) {
            submitData.isReformed = submitData.isReformed === '1' ? '1' : '0';
          }

          // 添加照片文件，只处理新上传的照片
          const newPhotos = this.photoList
            .filter(file => file.raw)
            .map(file => file.raw);

          // 如果是修改操作，添加待删除的照片ID
          if (this.form.houseId != null) {
            updateHouse({
              ...submitData,
              photos: newPhotos,
              deletedPhotoIds: this.deletedPhotoIds // 添加待删除的照片ID
            }).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.goBack();
            }).catch(error => {
              this.$modal.msgError("修改失败：" + error.message);
            });
          } else {
            addHouse({
              ...submitData,
              photos: newPhotos
            }).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.goBack();
            }).catch(error => {
              this.$modal.msgError("新增失败：" + error.message);
            });
          }
        }
      });
    },
    /** 取消按钮 */
    cancel() {
      this.goBack();
    },
    /** 返回按钮 */
    goBack() {
      this.$router.push({ path: "/house/house" });
    },
    /** 地图标记点移动事件 */
    handleMarkerMove(position) {
      this.form.longitude = position.longitude;
      this.form.latitude = position.latitude;
      // 调用地图组件的逆地理编码方法获取地址
      if (this.$refs.aMap) {
        this.$refs.aMap.reverseGeocode(position.longitude, position.latitude).then(result => {
          if (result && result.address) {
            // 更新详细地址
            this.form.address = result.address;
            
            // 可选：如果需要，也可以更新行政区划信息
            // if (result.addressComponent) {
            //   const { province, city, district, street } = result.addressComponent;
            //   // 更新行政区划选择器
            //   this.form.province = province;
            //   this.form.city = city;
            //   this.form.district = district;
            //   this.form.street = street;
              
            //   // 触发省份变更，以加载城市选项
            //   this.handleProvinceChange(province);
            // }
          }
        }).catch(error => {
          this.$message.error('获取地址信息失败：' + error.message);
        });
      } else {
        console.error('地图组件引用不存在');
      }
    },
    /** 更新地图位置 */
    updateMapLocation() {
      // 构建完整地址
      const fullAddress = [
        this.getRegionName('province'),
        this.getRegionName('city'),
        this.getRegionName('district'),
        this.getRegionName('street'),
        this.form.address
      ].filter(Boolean).join('');
      
      if (fullAddress) {
        // 调用地图组件的地理编码方法
        this.$refs.aMap?.geocodeAddress(fullAddress).then(result => {
          if (result && result.location) {
            this.form.longitude = result.location.lng;
            this.form.latitude = result.location.lat;
          }
        }).catch(error => {
          console.error('地理编码失败:', error);
        });
      }
    },
    /** 处理地址变化 */
    handleAddressChange() {
      this.updateMapLocation();
    },
    /** 获取地区名称 */
    getRegionName(type) {
      const options = {
        province: this.provinceOptions,
        city: this.cityOptions,
        district: this.districtOptions,
        street: this.streetOptions
      }[type];
      
      const value = this.form[type];
      if (value && options) {
        const found = options.find(item => item.value === value);
        return found ? found.label : '';
      }
      return '';
    },
    /** 获取照片列表 */
    getPhotoList(houseId) {
      listHousePhoto({ houseId: houseId, source: 'house' }).then(response => {
        const photoList = response.data || [];
        // 获取每张照片的URL
        const promises = photoList.map(photo => 
          getPhotoUrl(photo.photoId).then(res => ({
            ...photo,
            url: res.data,
            name: photo.originalName
          }))
        );
        Promise.all(promises).then(photos => {
          this.photoList = photos;
        });
      });
    },
    /** 文件上传之前的钩子 */
    handleBeforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isImage) {
        this.$message.error('只能上传JPG/PNG格式的图片！');
        return false;
      }
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    /** 文件上传成功的钩子 */
    handleUploadSuccess(file) {
      try {
        // 只有当file和file.raw存在时才处理
        if (file && file.raw) {
          const fileObj = {
            name: file.name,
            raw: file.raw,
            status: 'ready'
          };

          // 安全地创建预览URL
          try {
            fileObj.url = URL.createObjectURL(file.raw);
          } catch (e) {
            console.warn('创建预览URL失败:', e);
            fileObj.url = ''; // 设置一个默认值
          }

          this.photoList.push(fileObj);
          console.log('添加照片:', fileObj);
        } else {
          console.warn('文件对象无效:', file);
        }
      } catch (error) {
        console.error('处理上传文件时出错:', error);
      }
    },
    /** 文件上传失败的钩子 */
    handleUploadError() {
      this.$message.error("上传失败，请重试");
    },
    /** 文件超出个数限制的钩子 */
    handleUploadExceed() {
      this.$message.warning(`最多只能上传10张图片`);
    },
    /** 删除文件的钩子 */
    handleUploadRemove(file) {
      const index = this.photoList.findIndex(item => item.name === file.name);
      if (index !== -1) {
        const photo = this.photoList[index];
        // 如果是已有的图片（有photoId），记录到待删除列表
        if (photo.photoId) {
          this.deletedPhotoIds.push(photo.photoId);
        }
        // 如果存在预览URL，释放它
        if (photo.url) {
          try {
            URL.revokeObjectURL(photo.url);
          } catch (e) {
            console.warn('释放预览URL失败:', e);
          }
        }
        this.photoList.splice(index, 1);
      }
    },
    /** 加载项目选项数据 */
    loadProjectOptions() {
      listProjects({ pageSize: 1000 }).then(response => {
        this.projectOptions = response.rows;
        this.projectOptionsBackup = [...this.projectOptions]; // 保存一份完整数据用于筛选
      });
    },
    /** 项目名称筛选方法 */
    filterProjects(query) {
      if (query !== '') {
        this.projectOptions = this.projectOptionsBackup.filter(item => {
          return item.projectName.toLowerCase()
            .indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this.projectOptions = [...this.projectOptionsBackup];
      }
    },
    /** 清除项目选择时的处理 */
    handleProjectClear() {
      this.form.projectId = null;
      this.projectOptions = [...this.projectOptionsBackup];
    },
    loadAllUsers() {
      listUser({
        pageNum: 1,
        pageSize: 1000
      }).then(response => {
        this.userOptions = response.rows;
      });
    },
    /** 获取用户昵称 */
    getUserNickName(userName) {
      const user = this.userOptions.find(u => u.userName === userName);
      return user ? user.nickName : userName;
    }
  }
};
</script>

<style>
.block-container {
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}
.block-container:last-child {
  border-bottom: none;
  margin-bottom: 0;
}
.block-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}
.bottom-control {
  margin-top: 15px;
  text-align: center;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

/* 基本信息区域布局 */
.basic-info-container {
  display: flex;
  gap: 20px;
}

.form-section {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
}

.map-section {
  flex: 1;
  min-height: 400px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 设置当前页面数字输入框宽度与普通输入框一致 */
.el-input-number.el-input-number--medium {
  width: 100% !important;
}

.el-select {
  width: 100% !important;
}

.el-date-editor.el-input {
  width: 100% !important;
}

/* 添加照片上传样式 */
.el-upload--picture-card {
  width: 148px;
  height: 148px;
  line-height: 148px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 148px;
  height: 148px;
}

.el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style> 